package com.doge.walknovel.utils

import android.app.Activity
import android.app.NotificationManager
import android.content.Context
import android.content.ContextWrapper
import android.graphics.Bitmap
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.bumptech.glide.load.Transformation
import com.bumptech.glide.request.RequestOptions
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import io.reactivex.Observable
import jp.wasabeef.glide.transformations.RoundedCornersTransformation
import java.util.concurrent.TimeUnit

val systemWindowInsetsTop = MutableLiveData<Int>() // for home page
fun updateSystemWindowInsetsTop(value: Int) {
    if (systemWindowInsetsTop.value != value) systemWindowInsetsTop.value = value
}

fun View.setOnClickCallback(interval: Long = 700L, callback: (View) -> Unit) {
    if (!isClickable) isClickable = true
    if (!isFocusable) isFocusable = true
    Observable.create<View> {
        setOnClickListener(it::onNext)
    }.throttleFirst(interval, TimeUnit.MILLISECONDS)
        .doOnNext(callback)
        .subscribe()
}

fun Activity.closeKeyBoard(): Boolean {
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
    return imm?.hideSoftInputFromWindow(window.decorView.applicationWindowToken, 0) ?: false
}

fun Fragment.closeKeyBoard(): Boolean {
    val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
    val token = view?.applicationWindowToken ?: return false
    return imm?.hideSoftInputFromWindow(token, 0) ?: false
}

fun ViewGroup.inflate(resId: Int): View {
    return LayoutInflater.from(context).inflate(resId, this, false)
}

val View.activity: Activity?
    get() = getActivity(context) ?: Activities.top

// https://stackoverflow.com/questions/9273218/is-it-always-safe-to-cast-context-to-activity-within-view/45364110
private fun getActivity(context: Context?): Activity? {
    if (context == null) return null
    if (context is Activity) return context
    if (context is ContextWrapper) return getActivity(context.baseContext)
    return null
}

fun clearAllNotification() {
    try {
        val manager =
            appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        manager.cancelAll()
    } catch (e: Throwable) {
        e.printStackTrace()
    }
}

fun TabLayout.setupWithViewPager2(viewPager2: ViewPager2) {
    TabLayoutMediator(
        this, viewPager2, true
    ) { tab, position ->
        val title = (viewPager2.adapter as FragmentStateAdapter).getTitle(position)
        tab.text = title
    }.attach()
}

val RoundedCorners4 = RoundedCornersTransformation(4.dp, 0)
val RoundedCorners8 = RoundedCornersTransformation(8.dp, 0)
val RoundedCorners12 = RoundedCornersTransformation(12.dp, 0)
val CircleCrop = com.bumptech.glide.load.resource.bitmap.CircleCrop()


fun ImageView.load(
    url: String?,
    placeHolder: Int? = null,
    transformation: Transformation<Bitmap>? = null,
    width: Int?,
    height: Int?,
    type: Int? = 8,
    quality: Int = 75,
) {
    val thumbnail = if (type != null && (width != null || height != null)) {
        thumbnail(url, width ?: 0, height ?: 0, type, quality)
    } else url
    load(thumbnail, placeHolder, transformation)
}

private fun ImageView.load(
    url: String?, placeHolder: Int? = null,
    transformation: Transformation<Bitmap>? = null
) {
    // log("image load $url")
    if (url.isNullOrEmpty()) {
        setImageResource(placeHolder ?: android.R.color.transparent)
        return
    }

    var requestOptions = RequestOptions()
    if (placeHolder != null) {
        requestOptions = (requestOptions)
            .placeholder(placeHolder)
            .error(placeHolder)
    }
    if (transformation != null) {
        requestOptions = (requestOptions)
            .transform(transformation)
    }
    Glide.with(this).load(url)
        .apply(requestOptions)
        .into(this)
}